/*
 * Copyright 2021 yhuan416
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "sbull.h"
#include "sbull_internal.h"

int sbull_mtd_erase(struct MtdDev *mtd, UINT64 start, UINT64 bytes, UINT64 *failAddr)
{
    struct Sbull *sbull = NULL;

    if (mtd == NULL || mtd->priv == NULL) {
        return -1;
    }
    sbull = (struct Sbull *)mtd->priv;

    // 判断是否溢出
    if (start + bytes > mtd->size) {
        return -EINVAL;
    }

    // 判断是否对齐
    if (start & (mtd->eraseSize - 1)) {
        return -EINVAL;
    }

    // 判断是否对齐
    if (bytes & (mtd->eraseSize - 1)) {
        return -EINVAL;
    }

    memset((sbull->base + start), 0xff, bytes);
    return 0;
}

int sbull_mtd_read(struct MtdDev *mtd, UINT64 start, UINT64 bytes, const char *buf)
{
    struct Sbull *sbull = NULL;

    if (mtd == NULL || mtd->priv == NULL) {
        return -1;
    }
    sbull = (struct Sbull *)mtd->priv;

    // 判断是否溢出
    if ((start + bytes) > mtd->size) {
        return -EINVAL;
    }

    // 判断长度是否非0
    if (!bytes) {
        return 0;
    }

    memcpy((void *)buf, (void *)(sbull->base + start), bytes);
    return bytes;
}

int sbull_mtd_write(struct MtdDev *mtd, UINT64 start, UINT64 bytes, const char *buf)
{
    struct Sbull *sbull = NULL;

    if (mtd == NULL || mtd->priv == NULL) {
        return -1;
    }
    sbull = (struct Sbull *)mtd->priv;

    // 判断是否溢出
    if ((start + bytes) > mtd->size) {
        return -EINVAL;
    }

    // 判断长度是否非0
    if (!bytes) {
        return 0;
    }

    memcpy((void *)(sbull->base + start), (void *)buf, bytes);
    return bytes;
}
